using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Terra.Data.Entities;

namespace Terra.Data.Entities.Identity
{
    /// <summary>
    /// 权限实体
    /// </summary>
    [Table("Permissions")]
    [Comment("权限表")]
    [Index(nameof(Code), IsUnique = true, Name = "IX_Permission_Code")]
    public class Permission : AuditEntityBase<Guid>
    {
        /// <summary>
        /// 权限名称
        /// </summary>
        [Required]
        [StringLength(50)]
        [Comment("权限名称")]
        public string Name { get; set; }

        /// <summary>
        /// 权限编码
        /// </summary>
        [Required]
        [StringLength(100)]
        [Comment("权限编码，唯一标识")]
        public string Code { get; set; }

        /// <summary>
        /// 权限类型：menu-菜单权限，operation-操作权限，data-数据权限
        /// </summary>
        [Required]
        [StringLength(20)]
        [DefaultValue("operation")]
        [Comment("权限类型：menu-菜单权限，operation-操作权限，data-数据权限")]
        public string Type { get; set; }

        /// <summary>
        /// 菜单ID
        /// </summary>
        [Comment("关联的菜单ID")]
        public Guid? MenuId { get; set; }

        /// <summary>
        /// 权限描述
        /// </summary>
        [StringLength(200)]
        [Comment("权限描述")]
        public string Description { get; set; }

        /// <summary>
        /// 权限状态：1-启用，0-禁用
        /// </summary>
        [DefaultValue(1)]
        [Comment("权限状态：1-启用，0-禁用")]
        public int Status { get; set; }

        /// <summary>
        /// 是否系统权限
        /// </summary>
        [DefaultValue(false)]
        [Comment("是否系统权限，系统权限不可删除")]
        public bool IsSystem { get; set; }

        /// <summary>
        /// 关联的菜单
        /// </summary>
        [ForeignKey(nameof(MenuId))]
        public Menu Menu { get; set; }

        /// <summary>
        /// 生成权限编码
        /// </summary>
        /// <param name="menu">菜单实体</param>
        /// <param name="operation">操作类型（可选）</param>
        /// <returns>权限编码</returns>
        public static string GenerateCode(Menu menu, string operation = null)
        {
            // 菜单权限: menu:{menuName}
            // 按钮权限: menu:{menuName}:{operation}
            var code = $"menu:{menu.Name.ToLower()}";
            if (!string.IsNullOrEmpty(operation))
            {
                code = $"{code}:{operation.ToLower()}";
            }
            return code;
        }

        /// <summary>
        /// 生成权限名称
        /// </summary>
        /// <param name="menu">菜单实体</param>
        /// <param name="operation">操作类型（可选）</param>
        /// <returns>权限名称</returns>
        public static string GenerateName(Menu menu, string operation = null)
        {
            return string.IsNullOrEmpty(operation)
                ? $"{menu.Title}菜单权限"
                : $"{menu.Title}{operation}权限";
        }
    }
}
